package com.jy.datapipeline.export.quartz;

import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelSftp;
import com.jy.datapipeline.common.util.BeanFactoryUtil;
import com.jy.datapipeline.export.dao.ExpTaskExecuteDetailLogDao;
import com.jy.datapipeline.export.dao.repo.DataStoreInfoDaoRepo;
import com.jy.datapipeline.export.dao.repo.ExpRuleDaoRepo;
import com.jy.datapipeline.export.dao.repo.ExpTaskDaoRepo;
import com.jy.datapipeline.export.entity.DataStoreInfoModel;
import com.jy.datapipeline.export.entity.ExpRuleModel;
import com.jy.datapipeline.export.entity.ExpTaskExecuteDetailLogModel;
import com.jy.datapipeline.export.entity.ExpTaskExecuteLogModel;
import com.jy.datapipeline.export.entity.ExpTaskModel;
import com.jy.datapipeline.export.service.ExpTaskExecuteDetailLogService;
import com.jy.datapipeline.export.service.ExpTaskExecuteLogService;
import com.jy.datapipeline.common.util.FtpUtil;
import com.jy.datapipeline.common.util.TEAUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class JobDetailGetVerifyHandler extends QuartzJobBean {
    // @Autowired
    //private ExpTaskService expTaskService;
   // @Autowired
    private ExpTaskExecuteLogService expTaskExecuteLogService;
    //@Autowired
    private ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService;
    //@Value("${config.localStorePath}")
    private String  localStorePath;
    private DataStoreInfoModel dataStoreInfoModel;
    private DataStoreInfoDaoRepo dataStoreInfoDaoRepo;
    private ExpTaskDaoRepo expTaskDaoRepo;
    private ExpTaskExecuteDetailLogDao expTaskExecuteDetailLogDao;
    private ExpRuleDaoRepo expRuleDaoRepo;
    private ExpRuleModel expRuleModel;
    private ExpTaskModel expTaskModel;
    private ExpTaskExecuteLogModel expTaskExecuteLogModel;
    private int sumCount=0;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //查询正在执行中的任务
        try {
          //  expTaskService= BeanFactoryUtil.getBean(ExpTaskService.class);
            expTaskExecuteLogService= BeanFactoryUtil.getBean(ExpTaskExecuteLogService.class);
            expTaskExecuteDetailLogService=BeanFactoryUtil.getBean(ExpTaskExecuteDetailLogService.class);
            dataStoreInfoDaoRepo=BeanFactoryUtil.getBean(DataStoreInfoDaoRepo.class);
            localStorePath=(String) context.getJobDetail().getJobDataMap().get("localStorePath");
            expTaskDaoRepo=BeanFactoryUtil.getBean(ExpTaskDaoRepo.class);
            expTaskExecuteDetailLogDao=BeanFactoryUtil.getBean(ExpTaskExecuteDetailLogDao.class);
            expRuleDaoRepo=BeanFactoryUtil.getBean(ExpRuleDaoRepo.class);
        List<ExpTaskExecuteLogModel> list = expTaskExecuteLogService.findByStatus(1);

        if (list.size() > 0) {
            //查询任务明细
            for (int i = 0; i < list.size(); i++) {

                expTaskExecuteLogModel = list.get(i);
                 expTaskModel= expTaskDaoRepo.findByTaskId(expTaskExecuteLogModel.getTaskId());
                if(expTaskModel!=null){
                 dataStoreInfoModel = this.dataStoreInfoDaoRepo.findByStoreId(expTaskModel.getStoreId());
                    expRuleModel=this.expRuleDaoRepo.findByRuleId(expTaskModel.getRuleId());
                }

                List<ExpTaskExecuteDetailLogModel> logModelslist = this.expTaskExecuteDetailLogService.findBytaskExecutelogLogId(
                    expTaskExecuteLogModel.getTaskExecuteLogId());

                if (logModelslist.size() > 0) {
                    int sftpSucces = 0;
                    sumCount=0;
                    String verifyFileName = "";
                    StringBuilder verifySb = new StringBuilder();
                    for (int j = 0; j < logModelslist.size(); j++) {
                        ExpTaskExecuteDetailLogModel expTaskExecuteDetailLogModel = logModelslist.get(j);
                        if (expTaskExecuteDetailLogModel.getExpStatus() == 4) {

                           // log.info("datafile is ftpsuccess:{}",expTaskExecuteDetailLogModel.getDataFilePath());
                            JSONObject json = JSONObject.parseObject(expTaskExecuteDetailLogModel.getDataFileInfo());
                            if(json!=null && !json.isEmpty()){
                                verifySb.append(
                                    json.getString("fileName") + "|" + json.getString("fileSize") + "|" + json.getString("fileRow"));
                                    sumCount+=Integer.parseInt(json.getString("fileRow"));
                                verifySb.append("\n");
                                if(verifyFileName.equals("")){
                                        verifyFileName = expTaskExecuteDetailLogModel.getDataFileNamePrefix();
                                }
                                sftpSucces++;
                            }
                        }

                    }
                    if (sftpSucces == logModelslist.size()) {

                        //创建.verify 文件
                        BufferedWriter outVerify = null;
                        String verifyFilePath = "";

                        verifyFilePath = localStorePath + "/" + verifyFileName + ".verf";
                        File verifyFile = new File(verifyFilePath);
                        if (verifyFile.exists()) {
                            verifyFile.delete();
                            verifyFile = new File(verifyFilePath);
                        }
                        FileWriter verifyFileWriter = new FileWriter(verifyFile);
                        outVerify = new BufferedWriter(verifyFileWriter);
                        outVerify.write(verifySb.toString());
                        outVerify.flush();
                        log.info("create verify file path:{},fileName:{}",verifyFilePath,verifyFileName);
                        //修改二级任务状态
                       // this.expTaskExecuteLogService.updateExeuceStatus(expTaskExecuteLogModel.getTaskExecuteLogId(),4,0,"");

                        uploadBySftp(verifyFilePath,expRuleModel,expTaskExecuteLogModel);
                    }
                }
            }

        }

    }catch (Exception e){
            log.error("JobDetailGetVerifyHandler error",e);
        }
    }

    public void uploadBySftp(String file, ExpRuleModel expRuleModel,ExpTaskExecuteLogModel expTaskExecuteLogModel) {
        ChannelSftp channelSftp = null;
       // ExpTaskExecuteDetailLogModel expTaskExecuteDetailLogModel = null;
        try {
            log.info("start sftp connection");
            channelSftp = FtpUtil.connectBySftp(dataStoreInfoModel.getHost(),
                dataStoreInfoModel.getUserName(),
                TEAUtil.decode(dataStoreInfoModel.getPassword()));
            log.info("end sftp connection");

            FtpUtil.uploadFileBySftp(file, dataStoreInfoModel.getRemotePath(),
                channelSftp, expRuleModel.getIsFile());
            FtpUtil.disconnect(channelSftp);
            expTaskExecuteLogService.updateExeuceStatus(expTaskExecuteLogModel.getTaskExecuteLogId(),4,sumCount,file,"");
        } catch (Exception e) {
            log.error("uploadBySftp verify error ", e);
//            expTaskExecuteDetailLogModel.setErrorMsg(e.getMessage());
//            expTaskExecuteDetailLogModel.setExpStatus(-3);//上传异常
//            expTaskExecuteDetailLogModel.setSftpeEndtime(new Date());
//            expTaskExecuteDetailLogDao.updateExpStatus(expTaskExecuteDetailLogModel);
            expTaskExecuteLogService.updateExeuceStatus(expTaskExecuteLogModel.getTaskExecuteLogId(),3,sumCount,file,e.getMessage());
            FtpUtil.disconnect(channelSftp);
        }


    }
}
